import React from "react";
import bgimg from "../assests/login-bg.jpg";
import "../css/login.scss";
import { Form, Input, Button, Checkbox, message } from "antd";
import { useCallback } from "react";
import { connect } from "react-redux";
import request from "../utils/request";
function Login(props) {
  const onFinish = useCallback(({ username, password }) => {
    request.post("/users/login", { username, password }).then(({ data }) => {
      if (data.code === 1) {
        props.login(data.data);
        message.success("登录成功");
        props.history.push("/manage");
      } else {
        message.error('账号或密码错误')
      }
    });
  }, []);
  const onFinishFailed = useCallback(() => {
    message.error("请输入用户名和密码！");
  }, []);

  return (
    <div className="login_box" style={{ backgroundImage: `url(${bgimg})` }}>
      <Form
        name="basic"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        className="login_from"
      >
        <h2>后台管理系统</h2>
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            {
              required: true,
              message: "请输入用户名",
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: "请输入密码",
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="remember"
          valuePropName="checked"
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Checkbox>记住我</Checkbox>
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
Login = connect(
  () => {
    return {};
  },
  (dispatch) => {
    return {
      login(value) {
        dispatch({
          type: "login",
          payload: value,
        });
      },
    };
  }
)(Login);
export default Login;
